package com.iot.ig.controller;

import com.iot.ig.mqtt.gateway.MqttGateWay;
import com.iot.ig.mqtt.service.MqttService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * mqtt消息发布和订阅
 *
 */
@RestController
@RequestMapping("/mqtt")
@Slf4j
public class MqttController {

    @Resource
    private MqttGateWay mqttGateWay;

    @Resource
    private MqttService mqttService;

    /**
     * 发布消息
     *
     * @param topic
     * @param message
     * @return
     */
    @PostMapping("/sendMessage")
    public String sendMessage(String topic, String message) {
        log.info("发送消息,主题:{},消息:{}", topic, message);
        // 发送消息到指定topic
        if(topic == null || topic.isEmpty() || message == null || message.isEmpty()) {
            return "topic or message is null";
        }
        mqttGateWay.sendToMqtt(topic, 0, message);
        return "send topic: " + topic + ", message : " + message;
    }

    /**
     * 订阅消息
     * <p>
     * 订阅后会实时监听主题下的消息,已订阅的不会重复订阅
     * </p>
     *
     * @param topic
     * @return
     */
    @GetMapping("/subMessage")
    public void subMessage(@RequestParam String topic) {
        // 订阅消息topic
        log.info("订阅消息,主题:{}", topic);
        mqttService.addTopic(topic);
    }
}
